package com.atmc.service;

import com.atmc.bean.Authority;
import com.atmc.bean.Code;
import com.atmc.bean.Role;

import com.atmc.mapper.AuthorityMapper;
import com.atmc.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    CodeService codeService;
    @Autowired
    AuthorityMapper authorityMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Code user = codeService.selectOne(username);
        if (ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户不存在");
        }
        //给用户设置权限，可以对接数据库里的权限，或角色。
//        String str="vip,vip2";
//        Role role = roleMapper.selectRole(username);
        Authority authority = authorityMapper.selectOne(username);
        String role = authority.getRole();
//        String authorityString = role.getRole();

        List<GrantedAuthority> auth =AuthorityUtils.commaSeparatedStringToAuthorityList(role);

        org.springframework.security.core.userdetails.User result=new org.springframework.security.core.userdetails.User(
                user.getAcco_name(),new BCryptPasswordEncoder().encode(user.getAcco_password()), auth
        );

        return result;
    }
}
